package com.datagateway.controller;

import com.datagateway.component.DataSourceManager;
import com.datagateway.model.ProcessedData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 数据源管理控制器
 * 提供数据源的CRUD操作和监控接口
 * 
 * @author Data Gateway Team
 * @version 1.0.0
 */
@RestController
@RequestMapping("/api/datasource")
public class DataSourceController {

    private static final Logger logger = LoggerFactory.getLogger(DataSourceController.class);

    @Autowired
    private DataSourceManager dataSourceManager;

    /**
     * 获取支持的数据源类型
     */
    @GetMapping("/types")
    public ResponseEntity<Map<String, Object>> getSupportedTypes() {
        try {
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", dataSourceManager.getSupportedDataSourceTypes());
            response.put("message", "获取支持的数据源类型成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("获取支持的数据源类型失败: {}", e.getMessage(), e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取支持的数据源类型失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 创建数据源
     */
    @PostMapping("/create")
    public ResponseEntity<Map<String, Object>> createDataSource(
            @RequestParam String name,
            @RequestParam String type,
            @RequestBody Map<String, Object> config) {
        try {
            logger.info("创建数据源: name={}, type={}", name, type);
            
            boolean success = dataSourceManager.createDataSource(name, type, config);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", success);
            response.put("message", success ? "数据源创建成功" : "数据源创建失败");
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("创建数据源失败: name={}, type={}, error={}", name, type, e.getMessage(), e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "创建数据源失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 删除数据源
     */
    @DeleteMapping("/{name}")
    public ResponseEntity<Map<String, Object>> removeDataSource(@PathVariable String name) {
        try {
            logger.info("删除数据源: {}", name);
            
            boolean success = dataSourceManager.removeDataSource(name);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", success);
            response.put("message", success ? "数据源删除成功" : "数据源删除失败");
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("删除数据源失败: name={}, error={}", name, e.getMessage(), e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "删除数据源失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 获取所有数据源
     */
    @GetMapping("/list")
    public ResponseEntity<Map<String, Object>> getAllDataSources() {
        try {
            Map<String, DataSourceManager.DataSourceInstance> dataSources = dataSourceManager.getAllDataSources();
            
            Map<String, Object> dataSourceInfo = new HashMap<>();
            for (Map.Entry<String, DataSourceManager.DataSourceInstance> entry : dataSources.entrySet()) {
                Map<String, Object> info = new HashMap<>();
                info.put("type", entry.getValue().getType());
                info.put("connected", entry.getValue().isConnected());
                info.put("config", entry.getValue().getConfig());
                dataSourceInfo.put(entry.getKey(), info);
            }
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", dataSourceInfo);
            response.put("message", "获取数据源列表成功");
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("获取数据源列表失败: {}", e.getMessage(), e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取数据源列表失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 测试数据源连接
     */
    @PostMapping("/{name}/test")
    public ResponseEntity<Map<String, Object>> testConnection(@PathVariable String name) {
        try {
            logger.info("测试数据源连接: {}", name);
            
            boolean success = dataSourceManager.testConnection(name);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", success);
            response.put("message", success ? "数据源连接测试成功" : "数据源连接测试失败");
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("测试数据源连接失败: name={}, error={}", name, e.getMessage(), e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "测试数据源连接失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 写入数据到指定数据源
     */
    @PostMapping("/{name}/write")
    public ResponseEntity<Map<String, Object>> writeData(
            @PathVariable String name,
            @RequestBody List<ProcessedData> dataList) {
        try {
            logger.info("写入数据到数据源: name={}, count={}", name, dataList.size());
            
            boolean success = dataSourceManager.writeData(name, dataList);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", success);
            response.put("message", success ? "数据写入成功" : "数据写入失败");
            response.put("count", dataList.size());
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("写入数据失败: name={}, error={}", name, e.getMessage(), e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "写入数据失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 从指定数据源读取数据
     */
    @PostMapping("/{name}/read")
    public ResponseEntity<Map<String, Object>> readData(
            @PathVariable String name,
            @RequestParam(required = false) String query,
            @RequestBody(required = false) Map<String, Object> parameters) {
        try {
            logger.info("从数据源读取数据: name={}, query={}", name, query);
            
            List<ProcessedData> dataList = dataSourceManager.readData(name, query, parameters);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", dataList);
            response.put("count", dataList.size());
            response.put("message", "数据读取成功");
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("读取数据失败: name={}, error={}", name, e.getMessage(), e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "读取数据失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 执行SQL语句
     */
    @PostMapping("/{name}/execute")
    public ResponseEntity<Map<String, Object>> executeSql(
            @PathVariable String name,
            @RequestParam String sql,
            @RequestBody(required = false) Map<String, Object> parameters) {
        try {
            logger.info("执行SQL语句: name={}, sql={}", name, sql);
            
            boolean success = dataSourceManager.executeSql(name, sql, parameters);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", success);
            response.put("message", success ? "SQL执行成功" : "SQL执行失败");
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("执行SQL失败: name={}, error={}", name, e.getMessage(), e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "执行SQL失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 获取数据源统计信息
     */
    @GetMapping("/{name}/statistics")
    public ResponseEntity<Map<String, Object>> getStatistics(@PathVariable String name) {
        try {
            DataSourceManager.DataSourceStatistics statistics = dataSourceManager.getStatistics(name);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", statistics);
            response.put("message", "获取数据源统计信息成功");
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("获取数据源统计信息失败: name={}, error={}", name, e.getMessage(), e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取数据源统计信息失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 获取所有数据源统计信息
     */
    @GetMapping("/statistics")
    public ResponseEntity<Map<String, Object>> getAllStatistics() {
        try {
            Map<String, DataSourceManager.DataSourceStatistics> statistics = dataSourceManager.getAllStatistics();
            DataSourceManager.ManagerStatistics managerStats = dataSourceManager.getManagerStatistics();
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", statistics);
            response.put("manager", managerStats);
            response.put("message", "获取所有数据源统计信息成功");
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("获取所有数据源统计信息失败: {}", e.getMessage(), e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "获取所有数据源统计信息失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 更新数据源配置
     */
    @PutMapping("/config")
    public ResponseEntity<Map<String, Object>> updateConfiguration(
            @RequestParam boolean enabled,
            @RequestParam int maxConnections,
            @RequestParam long connectionTimeout,
            @RequestParam long queryTimeout,
            @RequestParam int batchSize,
            @RequestParam boolean autoCommit,
            @RequestParam boolean poolingEnabled,
            @RequestParam int poolSize,
            @RequestParam long poolTimeout) {
        try {
            logger.info("更新数据源管理器配置");
            
            dataSourceManager.setConfiguration(enabled, maxConnections, connectionTimeout, 
                queryTimeout, batchSize, autoCommit, poolingEnabled, poolSize, poolTimeout);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "数据源管理器配置更新成功");
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("更新数据源管理器配置失败: {}", e.getMessage(), e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "更新数据源管理器配置失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 关闭所有数据源
     */
    @PostMapping("/close-all")
    public ResponseEntity<Map<String, Object>> closeAllDataSources() {
        try {
            logger.info("关闭所有数据源连接");
            
            dataSourceManager.closeAllDataSources();
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "所有数据源连接已关闭");
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("关闭所有数据源连接失败: {}", e.getMessage(), e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "关闭所有数据源连接失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }
}
